<?php

class Model_Listing_Regular extends Model_Listing implements Model_Listing_Interface
{
    protected static  $_collection = 'listing';


    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
    );

    //protected $_category = array();

    public function __construct($data = array(), $config = array()) {
        static::$_transcript = array_merge(array(
        ), static::$_transcript);
        parent::__construct($data, $config);
        //$this->_category = $this->category;
    }
	
	public static function getTranslationFormField()
    {
        $arr = array(
			'tl_en' =>'text',
			'cs_en' =>'textarea',
			
		);
		
		return $arr;
    }
	
    public function postAnAddForm($options = array()) {
        $options = array_merge($options, array('category' => $this->category));
       	
        return new Listing_Form_PostAnAddRegularForm($options);
    }

    public function getAdDetailPartialName()
    {
        return '';
    }

    public function getAdPreviewPartialName()
    {
        return $this->getAdDetailPartialName();
    }

    public static function getSearchResultPartialName()
    {
        return 'regular';
    }

    public function __get($name)
    {
        return parent::__get($name);
    }

    public static function getRefineSearchForm($options)
    {
        return new Search_Form_RegularRefineForm($options);
    }

    public static function processRefineSearchForm(&$get, $page, $per_page, &$query, &$fields, &$additionalParameters)
    {

        $results = false;
        $fields  = array('description', 'title', 'area_l2_name', 'area_l1_name', 'street', 'model_name','make_name', 'username');

        $values     = array();
        $valuesplus = array();
        
        //s=defined search terms based on all verticals
        $search_terms = Model_Listing_Car::getSearchTextTerms() + 
                        Model_Listing_Boat::getSearchTextTerms() + 
                        Model_Listing_Motorcycle::getSearchTextTerms() + 
                        Model_Listing_Residential::getSearchTextTerms()+
                        Model_Listing_Commercial::getSearchTextTerms() +
                        Model_Listing_Maid::getSearchTextTerms() +
                        Model_Listing_Job::getSearchTextTerms();
        
        
        $exact_search_terms = Model_Listing_Residential::getExactSeachTerms() +
                              Model_Listing_Commercial::getExactSeachTerms() +
                              Model_Listing_Car::getExactSeachTerms() +
                              Model_Listing_Motorcycle::getExactSeachTerms() +
                              Model_Listing_Boat::getExactSeachTerms() +
                              Model_Listing_Maid::getExactSeachTerms() +
                              Model_Listing_Job::getExactSeachTerms();


        //var_dump($get, $page, $per_page, $query, $fields, $additionalParameters);exit;

        $q      = '';
        
        $qq     = empty($_GET['keyword']) ? '' : $_GET['keyword'];
        $to_add = ' ';
        $fq = '';

        //add the username
        if (!empty($get['keyword'])) {
            //$q = '(username_lower:"'.$get['keyword'].'"^50.0) ';
        }

        if (!empty($exact_search_terms)) {
            foreach($exact_search_terms as $name => $val) {
                foreach($val as $k => $v) {
                    foreach((array) $v as $v1) {
                        if (trim(strtolower($v1)) != 'all' && preg_match('#('.trim($v1).')#i', $get['keyword'], $match)) {
                            //var_dump($match, $v, $get['keyword'], str_ireplace( $v, '', $get['keyword']));
                            $get['keyword'] = str_ireplace( $v1, '', $get['keyword']);
                            $q .= $to_add.str_replace('_name', '', $name) .':'.$k.'^5.0 ';
                            $to_add = ' OR ';
                        }
                    }
                }
            }
            if (!empty($q) && !empty($tmp)) {
                $q = ' OR ('.$tmp.') ';
            }
        }
        
        $pattern = '#(?<=([0-9]))\s+bedroom[s]?#iu';
        if (preg_match($pattern, strtolower($get['keyword']), $match)) {
            $qq = str_ireplace($match[1].$match[0], '"'.$match[1].$match[0].'"', $qq);
            $get['keyword'] = str_ireplace($match[1].$match[0], '', $get['keyword']);
            $tmp = ' bedroom:'.trim($match[1]).'^9.0 ';
            if (!empty($q)) {
                $q .= ' OR ('.$tmp.') ';
            } else {
                $q = $tmp;
            }
        }
        
        $to_add = ' ';
        
        //remove quoted words and add them to q
        $bak = $get['keyword'];
        
        
        $arr = preg_match_all('#\"(.*?)\"#i', $get['keyword'], $match);
        foreach ($match[1] as $v) {
            $q .= ' AND "'.$v.'"';
        }
        $get['keyword'] = preg_replace('#"(.*?)"#i', '', $get['keyword']);

        $get['keyword'] = trim($get['keyword']);
        if (!empty($get['keyword'])) {
            if (!empty($q)) {
                $q.=' OR ';
            }
            $q .='(';
            foreach ($fields as $f) {
                $list = explode(' ', trim($get['keyword']));
                foreach($list as $vl) {
                    if (!empty($vl)) {
                        $q .= $to_add.''.$f.':'.$vl;
                        $to_add = ' OR ';
                    }
                }
            }
            $q.=') ';
        }
        
        
        $q.= ' OR _query_:"{!dismax qf=$qf v=$qq}" ';
        
        if (empty($_GET['keyword'])) {
            $q = '*:*';
        }
        
        $additionalParameters = array();

        if (!empty($q)) {
            $query = $q;
        }

        if (empty($query)) {
            $query = '*:*';
        }
    
        if (isset($get['sort'])) {
            $get['sort'] = empty($get['sort']) ? '' : $get['sort'];
        }
        
        switch ($get['sort']) {
            case 'highest':
                $get['sort'] = 'highest';
                $sort = 'price_sort desc';
                break;
            case 'lowest':
                $get['sort'] = 'lowest';
                $sort = 'price_sort asc';
                break;
            case 'rel':
                $get['sort'] = 'rel';
                $sort = 'score desc';
                break;
            case 'recent':
                $get['sort'] = 'recent';
                $sort = 'posted_at desc';
                break;
            case 'status':
                $get['sort'] = 'status';
                $sort = 'status desc';
                break;
            default:
                if (!empty($_GET['keyword'])) {
                    $get['sort']  = 'rel';
                    $sort         = 'score desc';
                } else {
                    $get['sort']  = 'recent';
                    $sort         = 'posted_at desc';
                }
        }
        
        $additionalParameters['fl']   = '*,score';
        $additionalParameters['sort'] = $sort;
        
        $qf = '';
        foreach($search_terms as $v => $weight) {
            $qf .= $v.'^'.$weight.' ';
        }
        
        if (!empty($qf)) {
            $additionalParameters['qf'] = $qf;
        }
        if (!empty($qq)) {
            $additionalParameters['qq']   = $qq;
        }  
        
       
        if (!empty($get['has_image'])) {
            $valuesplus['has_image'] = true;
        }

        if (!empty($get['city'])) {
            $valuesplus['city'] = (int) $_GET['city'];
        }

        if (isset($get['price']) && isset($get['price-1'])) {
            $price  = $get['price'];
            $price1 = $get['price-1'];
        }
        if (isset($price1)) { 
            $price1 = str_replace(',', '', $price1);
        }
        if (isset($price) && isset($price1)) {
            $test1 = false;$test2 = false;
            if (empty($price1)) {
                $price1 = '*';
                $test1 = true;
            }
            if (empty($price)) {
                $price = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['price'] = ' ['.intval(str_replace(',', '', $price)).' TO ' . $price1.']';
            }
        }
        
       // Area
        if (!empty($get['area_l1'])) {
            $valuesplus['area_l1'] = $get['area_l1'];
        }

        // District
        if (!empty($get['area_l2'])) {
            $valuesplus['area_l2'] = $get['area_l2'];
        }

        foreach($valuesplus as $k => $val) {
          $valuesplus[$k] = '+'.$k.':'.$val.' ';
        }

        if (!empty($category)) {
            $fq .= $category;
        }

        
        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
        
        Model_Listing_Car::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        Model_Listing_Motorcycle::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        Model_Listing_Residential::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        Model_Listing_Commercial::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        $additionalParameters['sort'] = $sort;
        //Model_Listing_Job::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        //echo "<PRE>"; print_r($fq);exit;
    }
    
    public static function getFacetedSearch(&$additionalParameters)
    {
        /*
        $additionalParameters['facet'] = 'true';
        $additionalParameters['facet.field'] = 'category_attached';
        $additionalParameters['f.category_attached.facet.mincount'] = '1';
*/
    }

    public function getQuickSearchTabs()
    {
        return array();
    }

    public function getQuickSearchForms()
    {

    }
    
    public function processRestForm()
    {

        $post = $_POST;
        $price          = !empty($_POST['price']) ? $_POST['price'] : '';

        if (!empty($price) && $_POST['price'] != '' && !is_numeric($_POST['price']) ) {
            //echo 'price empty';exit;
            throw new Ac_Exception_MissingInformation('Price is not valid');
        }

        if ($price == 0 ){
            $this->price = 0;
        } elseif(empty($price)) {
            
        } else {
            $this->price = (float)$price;
        }
//        $this->price                  = (float)$price;
        parent::processRestForm();
        return true;
    }
    
}
